<?php
namespace app\shops\controller;

use app\store\controller\Weixin;
use think\Session;
use think\Db;
use think\Model;

/**
 * 教师管理
 */
class Teacher extends Base
{
    /**
     * @throws
     * 教师列表
     * @return [type] [description]
     */
    public function index()
    {
// 获取配置信息
        $conf = config();
        // 分页信息
        $pageSize   = input('limit')    ? input('limit')    : $conf['paginate']['list_rows'];

        // 获取前台传过来的姓名查询条件
        $teacher_name = input('get.keywords') ? : "";
        $this->assign('teacher_name',$teacher_name);
        $pageParam['query']['teacher_name'] = $teacher_name;

        // 获取前台传过来的门店查询条件
        $store_id = input('get.keywords1') ? : "";
        $this->assign('keywords1',$store_id);
        $pageParam['query']['store_id'] = $store_id;

        // 列表显示所有教师
        $list = Db("teacher")->alias('t')->join('store sr', 't.store_id=sr.store_id')
            ->field('t.teacher_id, t.teacher_name, t.teacher_tel, sr.store_name, t.sex, t.can_use,t.openid')
            ->where('t.shop_id',$this->shop_id)
            ->where('t.teacher_name','like',"%{$teacher_name}%")
            ->where('sr.store_id','like',"%{$store_id}%")
            ->order("teacher_id desc")->paginate(['query'=>request()->param(),$pageSize]);

        // 获取门店信息列表
        $store_list = Db('store')->where('shop_id',$this->shop_id)->field('store_id, store_name')->select();

        $this->assign([
            'total'         => $list->total(),
            'page'          => $list->render(),
            'list'          => $list,
            'store_list'    => $store_list
        ]);


        return $this->fetch();

    }

    /**
     * 添加教师
     */
    public function add()
    {

        // 新增教师信息
        if(request()->isPost()){

            $data = [
                'shop_id'           => $this->shop_id,
                'store_id'          =>input('store_id'),
                'teacher_name'      => input('teacher_name'),
                'teacher_tel'       => input('teacher_tel'),
                'join_type'         => 1,
                'sex'               => input('sex'),
                'create_time'       => time(),
            ];

            $data['store_id'] = input('store_id');

            $re = Db("teacher") -> insert($data);

            if($re){
                $this->success("添加成功");
            }else{
                $this->error("网络错误");
            }

        }

        // 获取门店列表
        $store_list = Db('store')->where('shop_id',$this->shop_id)->field('store_id,store_name')->select();

        $this->assign('store_list', $store_list);

        return $this->fetch();
    }



    /**
     * @throws
     * 编辑教师信息
     */
    public function edit()
    {
        $teacher_id = input('teacher_id');
        // 更新数据
        if(request()->isAjax()){

            input('teacher_id')      == null || $data['teacher_id']       = input('teacher_id');
            input('teacher_name')    == null || $data['teacher_name']     = input('teacher_name');
            input('teacher_tel')     == null || $data['teacher_tel']      = input('teacher_tel');
            input('store_id')        == null || $data['store_id']         = input('store_id');
            input('sex')             == null || $data['sex']              = input('sex');

            $res = Db("teacher") ->where('shop_id',$this->shop_id) ->where('teacher_id',$teacher_id)->update($data);

            if($res===false){
                $this->error("编辑失败");
            }
            $this->success("编辑成功");

        }

        //拿到门店列表
        $store_list = Db('store')->field('store_name,store_id')->where('shop_id',$this->shop_id)->select();

        $this->assign('store_list',$store_list);

        //拿到该教师相关的信息
        $teacher_info = Db("teacher")->field('teacher_id, teacher_name, teacher_tel, shop_id, store_id, sex')
            ->where('shop_id',$this->shop_id) ->where('teacher_id',$teacher_id)->find();

        $this->assign('teacher_info',$teacher_info);

        return $this->fetch();
    }

    /**
     *教师的状态（正常/冻结）
     */
    public function is_use(){

        if (request()->isAjax()){
            // 获取参数
            $teacher_id     = input('teacher_id');
            $can_use        = input('can_use');

            // 更新老师状态
            $res = Db('teacher')->where('shop_id', $this->shop_id)->where('teacher_id', $teacher_id)->update(['can_use' => $can_use]);

            // 返回结果
            if($res){
                $this->success("成功");
            }else{
                $this->error("网络异常");
            }
        }

    }

    /**
     * @return mixed
     * 绑定是该教师的id
     */
    public function bind(){

        if (request()->isAjax()){
            //暂存教师id，为后面qrcode()提供teacher_id
            session::set("teacher_id",input('id'));
            if(session::get("teacher_id")){
                $this->success();
            }
            $this->error();
        }

        $this->assign('teacher_id',session::get("teacher_id"));
        return $this->fetch('index');
    }
    /**
     * 教师绑定二维码
     */
    public function qrcode()
    {



        // 教师id
        $teacher_id = session::get("teacher_id");


        $openid = Db('teacher')->where('shop_id',$this->shop_id) ->where('teacher_id',$teacher_id)->value('openid');

        // 查询老师在哪一个门店
        $store_id = Db("teacher")->where('shop_id',$this->shop_id)->where('teacher_id',$teacher_id)->value('store_id');

        // 微信获取授权地址
        $wx_request_url = request()->domain() . url("wchat/oauth/getwxinfo");
//        $wx_request_url = request()->domain() . url("store/wauth/getCode");


        // 回调地址
//        $teacher_call_bacl_url  = request()->domain() . url("teacher/teacher.first/qrcode");

        $param['store_id']= $store_id;
        $param['teacher_id']= $teacher_id;
        $param['type']= 'bind_teacher';
//        $param['shop_id']= $this->shop_id;
        $param['shop_id']= $this->shop_id;
        $teacher_call_bacl_url  = request()->domain() .url("store/teacher.index/wxinfo",$param);

        // 二维码链接
//        $url_arr['qr_teacher']  = $wx_request_url . "?shop_id=4&store_id={$store_id}&teacher_id={$teacher_id}&type=bind_teacher&call_back={$teacher_call_bacl_url}";
        $url_arr['qr_teacher']  = $wx_request_url . "?shop_id={$this->shop_id}&call_back={$teacher_call_bacl_url}";

        //微信 js config
        $weixin = new Weixin($this->shop_id);
        $access_token = $weixin->getAccessToken();
        $json_data=json_encode(array("action"=>"long2short","long_url"=>$url_arr['qr_teacher']));
        $result = $this->create_short_url($access_token,$json_data);

        $this->assign('url_arr',$result['short_url']);

        return $this->fetch();
    }


    public  function create_short_url($accesss_token='',$json_data){
        $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$accesss_token;
        $weixin = new Weixin($this->shop_id);
        $result = $weixin->https_request($url,$json_data);
        $jsoninfo = json_decode($result,true);
        return $jsoninfo;
    }
    //解绑二维码
    public function unbind(){

        if (request()->isAjax()){
            // 获取参数
            $data['teacher_id']     = input('teacher_id');
            $data['openid']         = '';
            $data['jx_openid']      = '';
            // 更新状态
            $res = Db('teacher')->where('shop_id', $this->shop_id)->where('teacher_id', $data['teacher_id'])->update($data);

            // 返回结果
            if($res){
                $this->success("成功");
            }else{
                $this->error("网络异常");
            }
        }

    }


}
